package lightrain.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import com.alibaba.fastjson.JSON;

public class DB {
	
	private  JdbcTemplate jdbcTemplate;
	
	
	public DB(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public  List<Map<String, Object>> queryList(String sql,Object...params){
		return jdbcTemplate.queryForList(sql, params);
	}
	
	public  Map<String, Object> queryMap(String sql,Object...params){
		return jdbcTemplate.queryForMap(sql, params);
	}
	
	public  <T> T queryUnique(String sql,Class<T> resultType,Object...params){
		return jdbcTemplate.queryForObject(sql, resultType, params);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T queryUnique(String sql,Object...params){
		return jdbcTemplate.query(sql, new ResultSetExtractor<T>(){
			@Override
			public T extractData(ResultSet rs) throws SQLException, DataAccessException {
				return (T) rs.getObject(0);
			}
			
		}, params); 
	}
	
	public  int update(String sql,Object...params){
		return jdbcTemplate.update(sql, params);
	}
	
	public  int delete(String sql,Object...params){
		return update(sql, params);
	}
	
	public  int insert(String sql,Object...params){
		return update(sql, params);
	}
	
	public  Long insertIdAuto(final String sql,final Object...params){
		GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con)throws SQLException {
				PreparedStatement statement = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				for (int j = 0; j <params.length; j++)
					statement.setObject((j+1),params[j]);
				return statement;
			}
		}, keyHolder);
		return keyHolder.getKey().longValue();
		
	}

	public  JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}



	public  void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	
	public DB(DataSource dataSource){
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
}
